import QtQuick 1.1
import Qt 4.7
//import com.nokia.symbian 1.1
import com.nokia.meego 1.0
import com.nokia.extras 1.1
import "platform.js" as PLATFORM
import "global.js" as GLOBAL
import NumismatMobile 1.0

Page {
    id: downloadDialog

    property string source: 'http://open-numismat-mobile.googlecode.com/files/collections.xml'
    property bool checkVersion: true

    property string __colorString: "color19-"
    property bool inverted: theme.inverted
    property string __invertedString: inverted? "-inverted" : ""

    signal accepted(string fileName)
    signal updateReady(string fileName)

    function setQuery() {
        if (checkVersion) {
            collectionModel.query = "/collections";
        }
        else {
            if (tabgroup.currentTab === tab1) {
                statusBar.text = qsTr("Catalogues");
                collectionModel.query = '/collections/collection[attribute::height="' + PLATFORM.HEIGHT + '"]';
            }
            else {
                statusBar.text = qsTr("Updates");
                collectionModel.query = '/collections/collection[attribute::height="' + PLATFORM.HEIGHT + '" and child::file="'+coinModel.fileTitle()+'.db"]/updates/update';
            }
        }
    }

    onStatusChanged: {
        if (status === PageStatus.Active || status === PageStatus.Activating) {
            statusBar.text = qsTr("Loading...");
            collectionModel.source = source;
            updateHeader.subtitleText = coinModel.fileTitle()
            setQuery();
        }
        else {
            collectionModel.source = '';
        }
    }

    Rectangle {
        anchors.fill: parent
        color: visual.colorBackgrond
    }

    XmlListModel {
        id: collectionModel

        query: '/collections'

        XmlRole { name: "title"; query: "title/string()" }
        XmlRole { name: "date"; query: "date/string()" }
        XmlRole { name: "size"; query: "size/string()" }
        XmlRole { name: "file"; query: "file/string()" }
        XmlRole { name: "url"; query: 'url/string()' }

        XmlRole { name: "version"; query: "@version/string()" }

        onStatusChanged: {
            if (status == XmlListModel.Error) {
                if (PLATFORM.TYPE === "symbian")
                    collectionModelError.open();
                else
                    collectionModelError.show();
            }
            if (status == XmlListModel.Ready) {
                if (checkVersion && collectionModel.count) {
                    if (collectionModel.get(0).version !== GLOBAL.VERSION) {
                        if (PLATFORM.TYPE === "symbian")
                            versionAvailable.open();
                        else
                            versionAvailable.show();
                    }

                    checkVersion = false;
                    setQuery();
                }
            }
        }
    }

    InfoBanner {
        id: collectionModelError
        anchors.bottom: PLATFORM.TYPE === "harmattan" ? parent.bottom : undefined
        text: qsTr("Can't open collections list ") + collectionModel.errorString();
    }

    InfoBanner {
        id: versionAvailable
        anchors.bottom: PLATFORM.TYPE === "harmattan" ? parent.bottom : undefined
        text: qsTr("New version of NumismatMobile is available!");
    }

    Component {
        id: fileListDelegate

        DownloadListItem {
            id: listItem
            titleText: title
//            subtitleText: file + ", " + size + ", " + Qt.formatDate(new Date(date))
            subtitleText: file + ", " + size + ", " + date

            function startDownload() {
                downloader.downloadFile(url, file);
            }

            onClicked: {
                if (downloader.checkFile(file)) {
                    overwriteConfirmation.accepted.connect(startDownload)
                    overwriteConfirmation.open();
                }
                else {
                    startDownload();
                }
            }
        }
    }

    Component {
        id: updateListDelegate

        DownloadListItem {
            id: listItem
            titleText: qsTr("Updates from %1").arg(date)
            subtitleText: size
            iconSource: coinModel.isApplied(date) ? (PLATFORM.TYPE === "harmattan" ?
                "image://theme/" + __colorString + "meegotouch-button-checkbox"+__invertedString+"-background-selected" :
                privateStyle.imagePath("qtg_graf_checkbox_normal_selected", false)) : ""

            onClicked: {
                if (!coinModel.isApplied(date)) {
                    downloader.downloadFile(url);
                }
                else {
                    if (PLATFORM.TYPE === "symbian")
                        alreadyAppliedError.open();
                    else
                        alreadyAppliedError.show();
                }
            }
        }
    }

    TabGroup {
        id: tabgroup
        currentTab: tab1
        width: parent.width
        anchors.top: parent.top
        anchors.bottom: parent.bottom

        onCurrentTabChanged: setQuery();

        Page {
            id: tab1
            ListView {
                id: fileList
                width: parent.width
                anchors.top: PLATFORM.TYPE === "harmattan" ? viewHeader.bottom : parent.top
                anchors.bottom: parent.bottom
                currentIndex: -1
                visible: !indicator.running

                delegate: fileListDelegate
                model: collectionModel
                highlightMoveSpeed: -1
            }
            ViewHeader {
                id: viewHeader
                visible: PLATFORM.TYPE === "harmattan"
                clickable: false
                titleText: qsTr("Catalogues")
            }
        }
        Page {
            id: tab2
            ListView {
                id: updatesList
                width: parent.width
                anchors.top: PLATFORM.TYPE === "harmattan" ? updateHeader.bottom : parent.top
                anchors.bottom: parent.bottom
                currentIndex: -1
                visible: !indicator.running

                delegate: updateListDelegate
                model: collectionModel
                highlightMoveSpeed: -1
            }
            ViewHeader {
                id: updateHeader
                visible: PLATFORM.TYPE === "harmattan"
                clickable: false
                titleText: qsTr("Updates for")
            }
        }
    }

    DownloadFile {
        id: downloader
        onStatusChanged: {
            if (status == DownloadFile.Ready) {
                pageStack.pop();
                if (tabgroup.currentTab === tab1)
                    accepted(file);
                else
                    updateReady(file);
            }
            else if (status == DownloadFile.Error) {
                if (PLATFORM.TYPE === "symbian")
                    downloaderError.open();
                else
                    downloaderError.show();
            }
        }
    }

    InfoBanner {
        id: downloaderError
        anchors.bottom: PLATFORM.TYPE === "harmattan" ? parent.bottom : undefined
        text: qsTr("Can't download collection ") + downloader.errorString();
    }

    InfoBanner {
        id: alreadyAppliedError
        anchors.bottom: PLATFORM.TYPE === "harmattan" ? parent.bottom : undefined
        text: qsTr("This update already applied");
    }

    BusyIndicator {
        id: indicator
        anchors.centerIn: parent
        visible: running
        running: (collectionModel.status == XmlListModel.Loading) || (downloader.status == DownloadFile.Loading)
        Component.onCompleted: {
            if (PLATFORM.TYPE === "symbian") {
                width = 96;
                height = 96;
            }
            else {
                platformStyle.size = "large";
            }
        }
    }

    QueryDialog {
        id: overwriteConfirmation
        titleText: qsTr("File exists")
        message: qsTr("File already exists. Overwrite?")
        acceptButtonText: qsTr("Yes")
        rejectButtonText: qsTr("Cancel")
    }

    tools: ToolBarLayout {
        ToolIcon {
            platformIconId: "toolbar-back"
            onClicked: pageStack.pop()
        }
        ButtonRow {
            TabButton {
                iconSource: "image://theme/icon-m-toolbar-list"
                tab: tab1
            }
            TabButton {
                iconSource: "image://theme/icon-m-toolbar-update"
                tab: tab2
            }
        }
    }
}
